package com.xf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xf.common.core.domain.DmpResult;
import com.xf.common.core.entity.dmp.DmpAuthPermission;
import com.xf.common.core.entity.dmp.DmpAuthResource;
import com.xf.common.core.entity.dmp.DmpAuthRole;
import com.xf.common.core.enums.UserCacheKeyEnum;
import com.xf.common.redis.cache.DmpRedisCache;
import com.xf.enums.PermissionTypeEnum;
import com.xf.enums.PermissionUserTypeEnum;
import com.xf.mapper.DmpAuthPermissionMapper;
import com.xf.mapper.DmpAuthRoleMapper;
import com.xf.service.DmpAuthPermissionService;
import com.xf.service.DmpAuthRoleService;
import com.xf.service.DmpAuthUserRoleRelationService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JoeyLiu
 * @create 2022-04-20 16:31
 */
@Service
public class DmpAuthRoleServiceImpl extends ServiceImpl<DmpAuthRoleMapper, DmpAuthRole> implements DmpAuthRoleService {

    @Resource
    private DmpAuthRoleMapper dmpAuthRoleMapper;

    @Resource
    private DmpAuthPermissionService dmpAuthPermissionService;


    @Autowired
    private DmpAuthUserRoleRelationService dmpAuthUserRoleRelationService;

    @Resource
    private DmpAuthPermissionMapper permissionDao;

    @Autowired
    private DmpRedisCache redisCache;


    @Override
    public IPage<DmpAuthRole> page(IPage page, String roleName, Integer state) {
        return dmpAuthRoleMapper.pageWithCreatedUser(page, roleName, state);
    }


    @Override
    public DmpAuthRole getByIdWith(Long id) {
        DmpAuthRole role = this.getById(id);
        List<DmpAuthPermission> permissionList = dmpAuthPermissionService.list(new LambdaQueryWrapper<DmpAuthPermission>()
                .eq(DmpAuthPermission::getUId, id).eq(DmpAuthPermission::getUType, PermissionUserTypeEnum.ROLE.getType()));
        //资源
        List<DmpAuthResource> resourceList = new ArrayList<>();
        permissionList.forEach(v -> {
            if (PermissionTypeEnum.RESOURCE.getType().equals(v.getRType())) {
                DmpAuthResource temp = new DmpAuthResource();
                temp.setId(v.getRId());
                resourceList.add(temp);
            }
        });
        role.setDmpAuthResources(resourceList);
        return role;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmpResult assign(DmpAuthRole role) {
        try {
            List<DmpAuthPermission> permissionList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(role.getDmpAuthResources())) {
                role.getDmpAuthResources().forEach(v -> {
                    DmpAuthPermission temp = new DmpAuthPermission();
                    temp.setUId(role.getId());
                    temp.setUType(PermissionUserTypeEnum.ROLE.getType());
                    temp.setRId(v.getId());
                    temp.setRType(PermissionTypeEnum.RESOURCE.getType());
                    permissionList.add(temp);
                });
            }
            permissionDao.deleteRolePermission(role.getId());
            redisCache.del(UserCacheKeyEnum.RESOURCE.getKey("ALL"));
            if (CollectionUtils.isNotEmpty(permissionList)) {
                dmpAuthPermissionService.saveBatch(permissionList);
            }
            return DmpResult.success("分配成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DmpResult.failed("分配失败");
        }
    }

    private List<Long> getPermissions(List<Long> roleIds) {
        List<DmpAuthPermission> permissionList = dmpAuthPermissionService.list(new LambdaQueryWrapper<DmpAuthPermission>().in(DmpAuthPermission::getUId, roleIds).eq(DmpAuthPermission::getUType, 1));
        if (CollectionUtils.isNotEmpty(permissionList)) {
            return permissionList.stream().map(DmpAuthPermission::getId).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    @Override
    public DmpResult insert(DmpAuthRole authRole) {

        baseMapper.insert(authRole);
        return DmpResult.success("添加成功");

    }

    @Override
    public DmpResult removeByRoleId(Long id) {
        try {
            baseMapper.deleteById(id);
            redisCache.del(UserCacheKeyEnum.RESOURCE.getKey("ALL"));
            return DmpResult.success("删除角色成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return DmpResult.failed("删除角色失败");
        }
    }

    @Override
    public DmpResult updateByRole(DmpAuthRole authRole) {
        try {
            baseMapper.updateById(authRole);
            redisCache.del(UserCacheKeyEnum.RESOURCE.getKey("ALL"));
            return DmpResult.success("修改角色成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return DmpResult.failed("修改角色失败");
        }
    }

}



